"""跟踪器管理器模块"""

from typing import Dict, Optional, List
from tracking.deep_sort_tracker import DeepSORTTracker
from config import get_config

class TrackerManager:
    """跟踪器管理器，负责管理多个目标跟踪器"""
    
    def __init__(self):
        """初始化跟踪器管理器"""
        self.trackers: Dict[str, DeepSORTTracker] = {}
        self.active_tracker_name: Optional[str] = None
        
        # 从配置加载跟踪器
        self._load_trackers_from_config()
    
    def _load_trackers_from_config(self) -> None:
        """从配置文件加载跟踪器配置"""
        # 创建默认的DeepSORT跟踪器
        default_tracker = DeepSORTTracker()
        self.trackers['default'] = default_tracker
        self.active_tracker_name = 'default'
        
        print("默认跟踪器已初始化")
    
    def create_tracker(self, tracker_name: str, **kwargs) -> bool:
        """创建新的跟踪器实例
        
        Args:
            tracker_name: 跟踪器名称
            **kwargs: 跟踪器参数
            
        Returns:
            是否创建成功
        """
        try:
            # 创建新的跟踪器实例
            tracker = DeepSORTTracker()
            
            # 设置参数
            if kwargs:
                tracker.set_parameters(**kwargs)
            
            # 添加到跟踪器字典
            self.trackers[tracker_name] = tracker
            
            print(f"跟踪器 '{tracker_name}' 已创建")
            
            # 如果是第一个创建的跟踪器，自动设置为活动跟踪器
            if self.active_tracker_name is None:
                self.set_active_tracker(tracker_name)
                
            return True
            
        except Exception as e:
            print(f"创建跟踪器 '{tracker_name}' 失败: {e}")
            return False
    
    def remove_tracker(self, tracker_name: str) -> bool:
        """移除指定的跟踪器
        
        Args:
            tracker_name: 跟踪器名称
            
        Returns:
            是否移除成功
        """
        try:
            # 不允许移除默认跟踪器
            if tracker_name == 'default':
                print("不能移除默认跟踪器")
                return False
            
            if tracker_name in self.trackers:
                del self.trackers[tracker_name]
                
                # 如果移除的是活动跟踪器，切换到默认跟踪器
                if tracker_name == self.active_tracker_name:
                    self.set_active_tracker('default')
                    print(f"自动切换到默认跟踪器")
                
                print(f"跟踪器 '{tracker_name}' 已移除")
                return True
            else:
                print(f"跟踪器 '{tracker_name}' 不存在")
                return False
                
        except Exception as e:
            print(f"移除跟踪器 '{tracker_name}' 失败: {e}")
            return False
    
    def set_active_tracker(self, tracker_name: str) -> bool:
        """设置活动跟踪器
        
        Args:
            tracker_name: 跟踪器名称
            
        Returns:
            是否设置成功
        """
        if tracker_name in self.trackers:
            self.active_tracker_name = tracker_name
            print(f"活动跟踪器已切换为: {tracker_name}")
            return True
        else:
            print(f"跟踪器 '{tracker_name}' 不存在")
            return False
    
    def get_active_tracker(self) -> Optional[DeepSORTTracker]:
        """获取当前活动的跟踪器
        
        Returns:
            DeepSORTTracker实例，如果没有活动跟踪器则返回None
        """
        if self.active_tracker_name and self.active_tracker_name in self.trackers:
            return self.trackers[self.active_tracker_name]
        return None
    
    def get_tracker(self, tracker_name: str) -> Optional[DeepSORTTracker]:
        """获取指定名称的跟踪器
        
        Args:
            tracker_name: 跟踪器名称
            
        Returns:
            DeepSORTTracker实例，如果跟踪器不存在则返回None
        """
        return self.trackers.get(tracker_name)
    
    def list_trackers(self) -> List[str]:
        """列出所有可用的跟踪器
        
        Returns:
            跟踪器名称列表
        """
        return list(self.trackers.keys())
    
    def get_active_tracker_name(self) -> Optional[str]:
        """获取当前活动跟踪器的名称
        
        Returns:
            活动跟踪器名称，如果没有活动跟踪器则返回None
        """
        return self.active_tracker_name
    
    def update_tracker_parameters(self, tracker_name: str, **kwargs) -> bool:
        """更新指定跟踪器的参数
        
        Args:
            tracker_name: 跟踪器名称
            **kwargs: 要更新的参数
            
        Returns:
            是否更新成功
        """
        tracker = self.get_tracker(tracker_name)
        if tracker:
            try:
                tracker.set_parameters(**kwargs)
                print(f"跟踪器 '{tracker_name}' 参数已更新")
                return True
            except Exception as e:
                print(f"更新跟踪器 '{tracker_name}' 参数失败: {e}")
                return False
        else:
            print(f"跟踪器 '{tracker_name}' 不存在")
            return False
    
    def clear_all_tracks(self) -> None:
        """清除所有跟踪器中的跟踪历史"""
        for tracker_name, tracker in self.trackers.items():
            tracker.clear_tracks()
        print("所有跟踪器的跟踪历史已清除")
    
    def get_tracking_statistics(self, tracker_name: str = None) -> Dict:
        """获取跟踪器统计信息
        
        Args:
            tracker_name: 跟踪器名称，如果为None则获取活动跟踪器的统计信息
            
        Returns:
            统计信息字典
        """
        if tracker_name:
            tracker = self.get_tracker(tracker_name)
        else:
            tracker = self.get_active_tracker()
        
        if tracker:
            stats = tracker.get_tracking_statistics()
            stats['tracker_name'] = tracker_name or self.active_tracker_name
            return stats
        return {}

# 创建全局跟踪器管理器实例
tracker_manager = TrackerManager()

# 导出常用方法
def get_active_tracker() -> Optional[DeepSORTTracker]:
    """获取当前活动跟踪器的快捷方法"""
    return tracker_manager.get_active_tracker()

def set_active_tracker(tracker_name: str) -> bool:
    """设置活动跟踪器的快捷方法"""
    return tracker_manager.set_active_tracker(tracker_name)

def list_available_trackers() -> List[str]:
    """列出所有可用跟踪器的快捷方法"""
    return tracker_manager.list_trackers()